import { FC, useCallback, useEffect, useState } from 'react';
import { Row, Col, Input, Switch } from 'antd';
import { debounce } from 'lodash';

import Collapse, { Panel } from '@/components/Collapse';
import Form, { useForm, Item as FormItem, useWatch } from '@/components/Form';
import { Content } from '@/components/Page';
import Button from '@/components/Button';
import AvatarUpload from '@/components/AvatarUpload';

import { getSystemInfoApi } from '@/services/service';
import { COMMON_REQUIRE_RULE } from '@/utils/config';
import request from '@/utils/request';
import notification from '@/utils/notification';
import { setOtherTypeValue } from '@/utils/renderer';

interface SysSettingProps {}

const SysSetting: FC<SysSettingProps> = () => {
  const [sysInfo, setSysInfo] = useState<any>({});
  const [loading, setLoading] = useState<boolean>(false);

  const [form] = useForm();

  const watchRbWatermarkFlag = useWatch('rbWatermarkFlag', form);

  useEffect(() => {
    setLoading(true);
    getSystemInfoApi()
      .then((res: any) => {
        setSysInfo(res);
        form.setFieldsValue(res);
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

  /** 保存 */
  const handSave = useCallback(
    debounce(async () => {
      // 表单未修改
      if (!form.isFieldsTouched()) return;

      // 校验获取值
      const fields = await form.validateFields();

      // 校验通过
      if (fields) {
        setLoading(true);
        request({
          url: '/system/config',
          method: 'PUT',
          data: { ...sysInfo, ...fields }
        })
          .then(async (res: any) => {
            if (res) {
              notification.success();
              // 修改成功系统设置后刷新页面
              window.location.reload();
            }
          })
          .finally(() => {
            setLoading(false);
          });
      }
    }, 500),
    [sysInfo]
  );

  return (
    <Content>
      <Collapse defaultActiveKey={['base']} ghost>
        <Panel
          header="基础设置"
          key="base"
          extra={
            <Button
              type="primary"
              onClick={(e: any) => {
                // 阻止冒泡
                e.stopPropagation();
                handSave();
              }}
            >
              保存
            </Button>
          }
        >
          <Form
            loading={loading}
            form={form}
            size="middle"
            labelCol={{ span: 4 }}
            initialValues={{ rbWatermarkFlag: 1 }}
          >
            <Row gutter={12}>
              <Col span={16}>
                <FormItem label="系统名" name="rbName" rules={[COMMON_REQUIRE_RULE]}>
                  <Input />
                </FormItem>
              </Col>
            </Row>
            <Row gutter={12}>
              <Col span={16}>
                <FormItem label="系统logo" name="rbLogoIcon">
                  <AvatarUpload />
                </FormItem>
              </Col>
            </Row>
            <Row gutter={12}>
              <Col span={16}>
                <FormItem
                  label="启用水印"
                  name="rbWatermarkFlag"
                  {...setOtherTypeValue(1, 0)}
                  valuePropName="checked"
                >
                  <Switch checkedChildren="是" unCheckedChildren="否" defaultChecked />
                </FormItem>
              </Col>
            </Row>
            <Row gutter={12}>
              <Col span={16}>
                <FormItem
                  label="自定义水印内容"
                  tooltip="默认为: 登录用户名-年/月/日; 启用水印才生效!"
                  name="rbWatermarkDesc"
                >
                  <Input disabled={!watchRbWatermarkFlag} />
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Panel>
      </Collapse>
    </Content>
  );
};

export default SysSetting;
